package bm.com.framework.common.encrypt;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

@Component
public class AESUtil implements InitializingBean {

    @Value("${sys.secretKey.apiKey}")
    private String key;

    public static final String CODE_TYPE = "UTF-8";

    public static final String AES_TYPE = "AES/CBC/PKCS5Padding";

    @Override
    public void afterPropertiesSet() throws Exception {

    }

    /**
     * 加密
     *
     * @param text
     * @return
     */
    public String encrypt(String text,String AES_KEY) {
        try {
            IvParameterSpec zeroIv = new IvParameterSpec(AES_KEY.getBytes());
            SecretKeySpec key = new SecretKeySpec(AES_KEY.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance(AES_TYPE);
            //CBC类型的可以在第三个参数传递偏移量zeroIv,ECB没有偏移量
            cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
            byte[] encryptedData = cipher.doFinal(text.getBytes(CODE_TYPE));
            byte[] encode = Base64.getEncoder().encode(encryptedData);

            return new String(encode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 解密
     *
     * @param encrypted
     * @return
     */
    public String decrypt(String encrypted) {
        try {
            return null;
//            byte[] byteMi = new BASE64Decoder().decodeBuffer(encrypted);
//            IvParameterSpec zeroIv = new IvParameterSpec(key.getBytes());
//            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
//            Cipher cipher = Cipher.getInstance(AES_TYPE);
//            //与加密时不同MODE:Cipher.DECRYPT_MODE
//            //CBC类型的可以在第三个参数传递偏移量zeroIv,ECB没有偏移量
//            cipher.init(Cipher.DECRYPT_MODE, keySpec, zeroIv);
//            byte[] decryptedData = cipher.doFinal(byteMi);
//            return new String(decryptedData, CODE_TYPE);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


}
